home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / copy.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  11KB  |  474 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Generic (shallow and deep) copying operations.
  5.  
  6. Interface summary:
  7.  
  8.         import copy
  9.  
  10.         x = copy.copy(y)        # make a shallow copy of y
  11.         x = copy.deepcopy(y)    # make a deep copy of y
  12.  
  13. For module specific errors, copy.Error is raised.
  14.  
  15. The difference between shallow and deep copying is only relevant for
  16. compound objects (objects that contain other objects, like lists or
  17. class instances).
  18.  
  19. - A shallow copy constructs a new compound object and then (to the
  20.   extent possible) inserts *the same objects* into it that the
  21.   original contains.
  22.  
  23. - A deep copy constructs a new compound object and then, recursively,
  24.   inserts *copies* into it of the objects found in the original.
  25.  
  26. Two problems often exist with deep copy operations that don\'t exist
  27. with shallow copy operations:
  28.  
  29.  a) recursive objects (compound objects that, directly or indirectly,
  30.     contain a reference to themselves) may cause a recursive loop
  31.  
  32.  b) because deep copy copies *everything* it may copy too much, e.g.
  33.     administrative data structures that should be shared even between
  34.     copies
  35.  
  36. Python\'s deep copy operation avoids these problems by:
  37.  
  38.  a) keeping a table of objects already copied during the current
  39.     copying pass
  40.  
  41.  b) letting user-defined classes override the copying operation or the
  42.     set of components copied
  43.  
  44. This version does not copy types like module, class, function, method,
  45. nor stack trace, stack frame, nor file, socket, window, nor array, nor
  46. any similar types.
  47.  
  48. Classes can use the same interfaces to control copying that they use
  49. to control pickling: they can define methods called __getinitargs__(),
  50. __getstate__() and __setstate__().  See the documentation for module
  51. "pickle" for information on these methods.
  52. '''
  53. import types
  54. from copy_reg import dispatch_table
  55.  
  56. class Error(Exception):
  57.     pass
  58.  
  59. error = Error
  60.  
  61. try:
  62.     from org.python.core import PyStringMap
  63. except ImportError:
  64.     PyStringMap = None
  65.  
  66. __all__ = [
  67.     'Error',
  68.     'copy',
  69.     'deepcopy']
  70.  
  71. def copy(x):
  72.     """Shallow copy operation on arbitrary Python objects.
  73.  
  74.     See the module's __doc__ string for more info.
  75.     """
  76.     cls = type(x)
  77.     copier = _copy_dispatch.get(cls)
  78.     if copier:
  79.         return copier(x)
  80.     copier = getattr(cls, '__copy__', None)
  81.     if copier:
  82.         return copier(x)
  83.     reductor = dispatch_table.get(cls)
  84.     if reductor:
  85.         rv = reductor(x)
  86.     else:
  87.         reductor = getattr(x, '__reduce_ex__', None)
  88.         if reductor:
  89.             rv = reductor(2)
  90.         else:
  91.             reductor = getattr(x, '__reduce__', None)
  92.             if reductor:
  93.                 rv = reductor()
  94.             else:
  95.                 raise Error('un(shallow)copyable object of type %s' % cls)
  96.             return reductor(x, rv, 0)
  97.  
  98. _copy_dispatch = d = { }
  99.  
  100. def _copy_immutable(x):
  101.     return x
  102.  
  103. for t in (type(None), int, long, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType, type(Ellipsis), types.FunctionType):
  104.     d[t] = _copy_immutable
  105.  
  106. for name in ('ComplexType', 'UnicodeType', 'CodeType'):
  107.     t = getattr(types, name, None)
  108.     if t is not None:
  109.         d[t] = _copy_immutable
  110.         continue
  111.  
  112.  
  113. def _copy_with_constructor(x):
  114.     return type(x)(x)
  115.  
  116. for t in (list, dict, set):
  117.     d[t] = _copy_with_constructor
  118.  
  119.  
  120. def _copy_with_copy_method(x):
  121.     return x.copy()
  122.  
  123. if PyStringMap is not None:
  124.     d[PyStringMap] = _copy_with_copy_method
  125.  
  126.  
  127. def _copy_inst(x):
  128.     if hasattr(x, '__copy__'):
  129.         return x.__copy__()
  130.     if hasattr(x, '__getinitargs__'):
  131.         args = x.__getinitargs__()
  132.         y = x.__class__(*args)
  133.     else:
  134.         y = _EmptyClass()
  135.         y.__class__ = x.__class__
  136.     if hasattr(x, '__getstate__'):
  137.         state = x.__getstate__()
  138.     else:
  139.         state = x.__dict__
  140.     if hasattr(y, '__setstate__'):
  141.         y.__setstate__(state)
  142.     else:
  143.         y.__dict__.update(state)
  144.     return y
  145.  
  146. d[types.InstanceType] = _copy_inst
  147. del d
  148.  
  149. def deepcopy(x, memo = None, _nil = []):
  150.     """Deep copy operation on arbitrary Python objects.
  151.  
  152.     See the module's __doc__ string for more info.
  153.     """
  154.     if memo is None:
  155.         memo = { }
  156.     
  157.     d = id(x)
  158.     y = memo.get(d, _nil)
  159.     if y is not _nil:
  160.         return y
  161.     cls = type(x)
  162.     copier = _deepcopy_dispatch.get(cls)
  163.     if copier:
  164.         y = copier(x, memo)
  165.     else:
  166.         
  167.         try:
  168.             issc = issubclass(cls, type)
  169.         except TypeError:
  170.             issc = 0
  171.  
  172.         if issc:
  173.             y = _deepcopy_atomic(x, memo)
  174.         else:
  175.             copier = getattr(x, '__deepcopy__', None)
  176.             if copier:
  177.                 y = copier(memo)
  178.             else:
  179.                 reductor = dispatch_table.get(cls)
  180.                 if reductor:
  181.                     rv = reductor(x)
  182.                 else:
  183.                     reductor = getattr(x, '__reduce_ex__', None)
  184.                     if reductor:
  185.                         rv = reductor(2)
  186.                     else:
  187.                         reductor = getattr(x, '__reduce__', None)
  188.                         if reductor:
  189.                             rv = reductor()
  190.                         else:
  191.                             raise Error('un(deep)copyable object of type %s' % cls)
  192.                         y = reductor(x, rv, 1, memo)
  193.                         memo[d] = y
  194.                         _keep_alive(x, memo)
  195.                         return y
  196.  
  197. _deepcopy_dispatch = d = { }
  198.  
  199. def _deepcopy_atomic(x, memo):
  200.     return x
  201.  
  202. d[type(None)] = _deepcopy_atomic
  203. d[type(Ellipsis)] = _deepcopy_atomic
  204. d[int] = _deepcopy_atomic
  205. d[long] = _deepcopy_atomic
  206. d[float] = _deepcopy_atomic
  207. d[bool] = _deepcopy_atomic
  208.  
  209. try:
  210.     d[complex] = _deepcopy_atomic
  211. except NameError:
  212.     pass
  213.  
  214. d[str] = _deepcopy_atomic
  215.  
  216. try:
  217.     d[unicode] = _deepcopy_atomic
  218. except NameError:
  219.     pass
  220.  
  221.  
  222. try:
  223.     d[types.CodeType] = _deepcopy_atomic
  224. except AttributeError:
  225.     pass
  226.  
  227. d[type] = _deepcopy_atomic
  228. d[xrange] = _deepcopy_atomic
  229. d[types.ClassType] = _deepcopy_atomic
  230. d[types.BuiltinFunctionType] = _deepcopy_atomic
  231. d[types.FunctionType] = _deepcopy_atomic
  232.  
  233. def _deepcopy_list(x, memo):
  234.     y = []
  235.     memo[id(x)] = y
  236.     for a in x:
  237.         y.append(deepcopy(a, memo))
  238.     
  239.     return y
  240.  
  241. d[list] = _deepcopy_list
  242.  
  243. def _deepcopy_tuple(x, memo):
  244.     y = []
  245.     for a in x:
  246.         y.append(deepcopy(a, memo))
  247.     
  248.     d = id(x)
  249.     
  250.     try:
  251.         return memo[d]
  252.     except KeyError:
  253.         pass
  254.  
  255.     for i in range(len(x)):
  256.         if x[i] is not y[i]:
  257.             y = tuple(y)
  258.             break
  259.             continue
  260.     else:
  261.         y = x
  262.     memo[d] = y
  263.     return y
  264.  
  265. d[tuple] = _deepcopy_tuple
  266.  
  267. def _deepcopy_dict(x, memo):
  268.     y = { }
  269.     memo[id(x)] = y
  270.     for key, value in x.iteritems():
  271.         y[deepcopy(key, memo)] = deepcopy(value, memo)
  272.     
  273.     return y
  274.  
  275. d[dict] = _deepcopy_dict
  276. if PyStringMap is not None:
  277.     d[PyStringMap] = _deepcopy_dict
  278.  
  279.  
  280. def _keep_alive(x, memo):
  281.     '''Keeps a reference to the object x in the memo.
  282.  
  283.     Because we remember objects by their id, we have
  284.     to assure that possibly temporary objects are kept
  285.     alive by referencing them.
  286.     We store a reference at the id of the memo, which should
  287.     normally not be used unless someone tries to deepcopy
  288.     the memo itself...
  289.     '''
  290.     
  291.     try:
  292.         memo[id(memo)].append(x)
  293.     except KeyError:
  294.         memo[id(memo)] = [
  295.             x]
  296.  
  297.  
  298.  
  299. def _deepcopy_inst(x, memo):
  300.     if hasattr(x, '__deepcopy__'):
  301.         return x.__deepcopy__(memo)
  302.     if hasattr(x, '__getinitargs__'):
  303.         args = x.__getinitargs__()
  304.         args = deepcopy(args, memo)
  305.         y = x.__class__(*args)
  306.     else:
  307.         y = _EmptyClass()
  308.         y.__class__ = x.__class__
  309.     memo[id(x)] = y
  310.     if hasattr(x, '__getstate__'):
  311.         state = x.__getstate__()
  312.     else:
  313.         state = x.__dict__
  314.     state = deepcopy(state, memo)
  315.     if hasattr(y, '__setstate__'):
  316.         y.__setstate__(state)
  317.     else:
  318.         y.__dict__.update(state)
  319.     return y
  320.  
  321. d[types.InstanceType] = _deepcopy_inst
  322.  
  323. def _reconstruct(x, info, deep, memo = None):
  324.     if isinstance(info, str):
  325.         return x
  326.     if not isinstance(info, tuple):
  327.         raise AssertionError
  328.     n = len(info)
  329.     if not n in (2, 3, 4, 5):
  330.         raise AssertionError
  331.     (callable, args) = info[:2]
  332.     if n > 3:
  333.         listiter = info[3]
  334.     else:
  335.         listiter = None
  336.     if n > 4:
  337.         dictiter = info[4]
  338.     else:
  339.         dictiter = None
  340.     if deep:
  341.         args = deepcopy(args, memo)
  342.     
  343.     y = callable(*args)
  344.     memo[id(x)] = y
  345.     if listiter is not None:
  346.         for item in listiter:
  347.             if deep:
  348.                 item = deepcopy(item, memo)
  349.             
  350.             y.append(item)
  351.         
  352.     
  353.     if dictiter is not None:
  354.         for key, value in dictiter:
  355.             if deep:
  356.                 key = deepcopy(key, memo)
  357.                 value = deepcopy(value, memo)
  358.             
  359.             y[key] = value
  360.         
  361.     
  362.     if state:
  363.         if deep:
  364.             state = deepcopy(state, memo)
  365.         
  366.         if hasattr(y, '__setstate__'):
  367.             y.__setstate__(state)
  368.         elif isinstance(state, tuple) and len(state) == 2:
  369.             (state, slotstate) = state
  370.         else:
  371.             slotstate = None
  372.         if state is not None:
  373.             y.__dict__.update(state)
  374.         
  375.         if slotstate is not None:
  376.             for key, value in slotstate.iteritems():
  377.                 setattr(y, key, value)
  378.             
  379.         
  380.     
  381.     return y
  382.  
  383. del d
  384. del types
  385.  
  386. class _EmptyClass:
  387.     pass
  388.  
  389.  
  390. def _test():
  391.     l = [
  392.         None,
  393.         1,
  394.         0x2L,
  395.         3.14,
  396.         'xyzzy',
  397.         (1, 0x2L),
  398.         [
  399.             3.14,
  400.             'abc'],
  401.         {
  402.             'abc': 'ABC' },
  403.         (),
  404.         [],
  405.         { }]
  406.     l1 = copy(l)
  407.     print l1 == l
  408.     l1 = map(copy, l)
  409.     print l1 == l
  410.     l1 = deepcopy(l)
  411.     print l1 == l
  412.     
  413.     class C:
  414.         
  415.         def __init__(self, arg = None):
  416.             self.a = 1
  417.             self.arg = arg
  418.             if __name__ == '__main__':
  419.                 import sys as sys
  420.                 file = sys.argv[0]
  421.             else:
  422.                 file = __file__
  423.             self.fp = open(file)
  424.             self.fp.close()
  425.  
  426.         
  427.         def __getstate__(self):
  428.             return {
  429.                 'a': self.a,
  430.                 'arg': self.arg }
  431.  
  432.         
  433.         def __setstate__(self, state):
  434.             for key, value in state.iteritems():
  435.                 setattr(self, key, value)
  436.             
  437.  
  438.         
  439.         def __deepcopy__(self, memo = None):
  440.             new = self.__class__(deepcopy(self.arg, memo))
  441.             new.a = self.a
  442.             return new
  443.  
  444.  
  445.     c = C('argument sketch')
  446.     l.append(c)
  447.     l2 = copy(l)
  448.     print l == l2
  449.     print l
  450.     print l2
  451.     l2 = deepcopy(l)
  452.     print l == l2
  453.     print l
  454.     print l2
  455.     l.append({
  456.         l[1]: l,
  457.         'xyz': l[2] })
  458.     l3 = copy(l)
  459.     import repr as repr
  460.     print map(repr.repr, l)
  461.     print map(repr.repr, l1)
  462.     print map(repr.repr, l2)
  463.     print map(repr.repr, l3)
  464.     l3 = deepcopy(l)
  465.     import repr as repr
  466.     print map(repr.repr, l)
  467.     print map(repr.repr, l1)
  468.     print map(repr.repr, l2)
  469.     print map(repr.repr, l3)
  470.  
  471. if __name__ == '__main__':
  472.     _test()
  473.  
  474.